import { NgIf, NgStyle } from '@angular/common';
import { ChangeDetectorRef, Component, ElementRef, inject, OnInit, ViewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Observable, of } from 'rxjs';

import { fnGetUUID } from '@app/utils/tools';
import { BasicConfirmModalComponent } from '@app/widget/base-modal';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NZ_MODAL_DATA, NzModalRef } from 'ng-zorro-antd/modal';
import { NzTableModule, NzTableQueryParams } from 'ng-zorro-antd/table';
import { NzTagModule } from 'ng-zorro-antd/tag';

import { CustomColumn } from '../../widget-default-setting';

@Component({
  selector: 'app-datasource-setting-modal',
  standalone: true,
  imports: [NzTagModule, NgIf, NzInputModule, FormsModule, NzTableModule, NgStyle, NzButtonModule],
  templateUrl: './datasource-setting-modal.component.html',
  styleUrl: './datasource-setting-modal.component.less'
})
export class DataSourceSettingModalComponent extends BasicConfirmModalComponent implements OnInit {
  tags = ['标题', '描述'];
  inputVisible = false;
  inputValue = '';
  editId: string | null = null;
  readonly nzModalData: NzSafeAny = inject(NZ_MODAL_DATA);
  dataSourceList: NzSafeAny[] = this.nzModalData.dataSourceList;
  customColumn: CustomColumn[] = this.nzModalData.customColumn;
  @ViewChild('inputElement', { static: false }) inputElement?: ElementRef;

  constructor(
    override modalRef: NzModalRef,
    private readonly cdr: ChangeDetectorRef
  ) {
    super(modalRef);
  }

  protected override getCurrentValue(): Observable<NzSafeAny> {
    return of({ dataSourceList: this.dataSourceList, customColumn: this.customColumn.filter(r => r.name != '操作') });
  }

  handleClose(removedTag: {}): void {
    this.tags = this.tags.filter(tag => tag !== removedTag);
  }

  startEdit(id: string): void {
    this.editId = id;
  }

  stopEdit(): void {
    this.editId = null;
  }

  deleteRecord(id: number): void {
    const rIndex = this.dataSourceList.findIndex(r => r.id === id);
    this.dataSourceList.splice(rIndex, 1);
  }

  sliceTagName(tag: string): string {
    const isLongTag = tag.length > 20;
    return isLongTag ? `${tag.slice(0, 20)}...` : tag;
  }

  getDataSourceData(e?: NzTableQueryParams): void {}

  showInput(): void {
    this.inputVisible = true;
    setTimeout(() => {
      this.inputElement?.nativeElement.focus();
    }, 10);
  }

  handleInputConfirm(): void {
    if (this.inputValue && this.tags.indexOf(this.inputValue) === -1) {
      this.tags = [...this.tags, this.inputValue];
      const columnName = fnGetUUID();
      this.insertColumn({
        name: this.inputValue,
        value: columnName,
        default: true,
        width: 200
      });
      this.dataSourceList.forEach(item => {
        item[columnName] = '空';
      });
    }
    this.inputValue = '';
    this.inputVisible = false;
  }

  insertLine(): void {
    let newLine: NzSafeAny = {};
    const keys = this.customColumn.map(r => r.value);
    keys.forEach((key: string) => {
      if (key === 'action') {
        newLine[key] = '删除';
      } else {
        newLine[key] = '空';
      }
    });
    this.dataSourceList.push(newLine);
  }

  insertColumn(column: CustomColumn): void {
    let index = this.customColumn.length - 1;
    this.customColumn.splice(index, 0, column);
    this.cdr.detectChanges();
  }

  initTable(): void {
    const containAction = this.customColumn.some(r => r.value == 'action');
    if (!containAction) {
      this.customColumn.push({
        name: '操作',
        value: 'action',
        default: true,
        required: true,
        position: 'right',
        width: 200
      });
    }

    this.dataSourceList.forEach(item => {
      if (!item.action) {
        item.action = '删除';
      }
    });
  }

  ngOnInit(): void {
    this.initTable();
  }
}
